<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="clientName">
        <el-input
          v-model="queryParams.clientName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱地址" prop="emailAddr">
        <el-input
          v-model="queryParams.emailAddr"
          placeholder="请输入邮箱地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="机器人数量" prop="robotNum">
        <el-input
          v-model="queryParams.robotNum"
          placeholder="请输入机器人数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:client:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:client:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:client:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:client:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="clientList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="ID" align="center" prop="id" /> -->
      <el-table-column label="用户名" align="center" prop="clientName" />
      <el-table-column label="邮箱地址" align="center" prop="emailAddr" />
      <el-table-column label="钱包余额" align="center" prop="walletBalance" />
      <el-table-column label="钱包密钥" align="center" prop="walletKey" />
      <el-table-column label="审核状态" align="center" prop="walletStatus" >

        <template slot-scope="scope">
          <p v-if="scope.row.walletStatus==0" style="">未审核</p>
          <p v-if="scope.row.walletStatus==null">未审核</p>
          <p v-else-if="scope.row.walletStatus==1">审核通过</p>
          <p v-else-if="scope.row.walletStatus==2">审核失败</p>
        </template>
      </el-table-column>
<!--
      <el-table-column label="机器人数量" align="center" prop="robotNum" />
      <el-table-column label="机器人超时时间" align="center" prop="robotExTime" /> -->
      <el-table-column label="注册时间" align="center" prop="registeredTime" />
      <el-table-column label="机器人" align="center"  >
        <template slot-scope="scope">
          <el-button
            size="minio"
            type="text"
            icon="el-icon-view"
            @click="handleRobotList(scope.row)"
            >
            关联机器人列表
          </el-button>
        <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-plus-outline"
            @click="handleAddRobot(scope.row)"
          >关联机器人</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button  v-if="scope.row.walletStatus==0"
            size="mini"
            type="text"
            icon="el-icon-wallet"
            @click="handleAudit(scope.row)"
            v-hasPermi="['system:client:edit']"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-wallet"
            @click="startAll(scope.row)"
            v-hasPermi="['system:client:edit']"
          >全部启动</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-wallet"
            @click="stopAll(scope.row)"
            v-hasPermi="['system:client:edit']"
          >全部停止</el-button>
          <el-dropdown trigger="click" :hide-on-click="false" @command="hanlderCommand($event, scope.row)">
            <span class="el-dropdown-link">
              单个启动<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item  v-for="option in scope.row.robots" :key="option.robotId" :command="option.robotId">
                <label>
                  <input type="checkbox" v-model="scope.row.selectedRobots" :onChange="handlerChangeCheckbox(scope)" :value="option.robotId">
                  {{ option.robotName }}
                </label>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:client:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:client:remove']"
          >删除</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库用户管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="clientName">
          <el-input v-model="form.clientName" placeholder="请输入用户名" :disabled="true"/>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="emailAddr">
          <el-input v-model="form.emailAddr" placeholder="请输入邮箱地址" :disabled="true"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input   v-model="form.password" placeholder="请输入密码" :disabled="true" />
        </el-form-item>
        <el-form-item label="钱包秘钥" prop="walletKey">
          <el-input v-model="form.walletKey" :disabled="true"/>
        </el-form-item>
        <el-form-item label="钱包审核" prop="walletStatus" >
          <p v-if="form.walletStatus==0" >未审核</p>
          <p v-else-if="form.walletStatus==null" >未审核</p>
          <p v-else-if="form.walletStatus==1" >审核通过</p>
          <p v-else-if="form.walletStatus==2" >审核失败</p>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

     <!-- 添加或修改仓库用户管理对话框 -->
     <el-dialog :title="title" :visible.sync="auditOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="clientName">
          <el-input v-model="form.clientName" :disabled="true"/>
        </el-form-item>
        <el-form-item label="钱包秘钥" prop="walletKey">
          <el-input v-model="form.walletKey" :disabled="true"/>
        </el-form-item>
        <el-form-item label="钱包审核" prop="walletStatus">
          <el-se v-model="form.walletStatus" />
          <el-radio v-model="form.walletStatus" label="1" >审核通过</el-radio>
          <el-radio v-model="form.walletStatus" label="2" >审核失败</el-radio>
        </el-form-item>
        <!-- <el-form-item v-if="form.walletStatus>0" label="钱包审核" prop="walletStatus">
          <p v-if="form.walletStatus==1" >审核通过</p>
          <p v-else-if="form.walletStatus==2" >审核失败</p>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 机器人列表 -->
    <el-dialog title="机器人列表" :visible.sync="robotListOpen" append-to-body>
      <el-table v-loading="loading" :data="robotList">
        <el-table-column label="机器人名称" align="center" prop="robotName" />
        <el-table-column label="机器人类型" align="center" prop="robotTypeName" />
        <el-table-column label="机器人过期时间" align="center" prop="robotExpiredTime" />
        <el-table-column label="操作" width="280" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRobotUpdate(scope.row)"
             v-hasPermi="['system:robot:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleRobotDelete(scope.row)"
              v-hasPermi="['system:robot:remove']"
            >删除</el-button>

          </template>
        </el-table-column>
    </el-table>
    <pagination
      v-show="queryRobotParams.total>0"
      :total="queryRobotParams.total"
      :page.sync="queryRobotParams.pageNum"
      :limit.sync="queryRobotParams.pageSize"
      @pagination="getRobotList()"
    />
    </el-dialog>
    <!-- 关联机器人 -->
    <el-dialog title="关联机器人" :visible.sync="addRobotOpen" width="500px" append-to-body>
          <el-form ref="robotForm" :model="robotForm" :rules="robotRules" label-width="120px">
        <el-form-item label="用户名称" prop="clientName">
          <el-input v-model="robotForm.clientName" placeholder="请输入用户名称"  :disabled="true"/>
        </el-form-item>
        <el-form-item label="选择机器人" prop="robotName">
          <el-select v-model="robotForm.robotName" multiple placeholder="请选择机器人">
              <el-option
                v-for="item in robotTypeOptions"
                :key="item.robotId"
                :label="item.robotName"
                :value="item.robotId">
              </el-option>
            </el-select>
        </el-form-item>
        <!-- <el-form-item label="机器人名称" prop="robotName">
          <el-input v-model="robotForm.robotName" placeholder="请输入机器人名称" />
        </el-form-item>
        <el-form-item label="机器人轨迹" prop="robotTrajectory">
          <el-input v-model="robotForm.robotTrajectory" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
        <el-form-item label="机器人过期时间" prop="robotExpiredTime">
          <el-date-picker clearable
            v-model="robotForm.robotExpiredTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择机器人过期时间">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
        </el-form-item> -->
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="robotForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRobotForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改用户机器人对话框 -->
    <el-dialog :title="title" :visible.sync="auditRobotOpen" width="500px" append-to-body>
      <el-form ref="robotForm" :model="robotForm" :rules="rules" label-width="80px">
       
        <el-form-item label="机器人类型名称" prop="robotTypeName">
          <el-input v-model="robotForm.robotTypeName" placeholder="请输入机器人类型名称" :disabled="true"/>
        </el-form-item>
        <el-form-item label="机器人名称" prop="robotName">
          <el-input v-model="robotForm.robotName" placeholder="请输入机器人名称" />
        </el-form-item>
        <el-form-item label="机器人轨迹" prop="robotTrajectory">
          <el-input v-model="robotForm.robotTrajectory" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="机器人过期时间" prop="robotExpiredTime">
          <el-date-picker clearable
            v-model="robotForm.robotExpiredTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择机器人过期时间">
          </el-date-picker>
        </el-form-item>
       
        <el-form-item label="备注" prop="remark">
          <el-input v-model="robotForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRobotForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
       
      
    </el-dialog>
  </div>
</template>

<script>
import { listClient, getClient, delClient, addClient, updateClient } from "@/api/system/client";
import { listRobot, addRobot ,getRobot ,updateRobot ,delRobot} from "@/api/system/robot";
import { listType } from "@/api/system/type"
import {
  sendWebsocket
} from '@/api/tool/gen'

export default {
  name: "Client",
  dicts: ['sys_robot_type', 'sys_normal_disable'],
  data() {
    return {
      robotList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      robotList: [], // 机器人列表
      // 仓库用户管理表格数据
      clientList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      auditOpen:false,
      robotListOpen: false,
      auditRobotOpen: false,
      addRobotOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        clientName: null,
        emailAddr: null,
        robotNum: null,
        clientId: null,
      },
      queryRobotParams: {
        pageNum: 1,
        pageSize: 10,
        clientName: null,
        emailAddr: null,
        robotNum: null,
        clientId: null,
      },
      // 表单参数
      form: {},
      robotForm: {},
      robotRules: {
        robotTypeId: [
          { required: true, message: "类型不能为空", trigger: "blur" }
        ],
        robotName: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        robotTrajectory: [
          { required: true, message: "轨迹不能为空", trigger: "blur" }
        ],
      },
      // 表单校验
      rules: {
        clientName: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        emailAddr: [
          { required: true, message: "邮箱地址不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ],
      },
      robotTypeOptions: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询仓库用户管理列表 */
    getList() {
      this.loading = true;
      listClient(this.queryParams).then(response => {
        this.clientList = response.rows.map(item => {
          if (item.robots) {
            item.selectedRobots = item.robots.filter(i => i.status === '1').map(i => i.robotId)
          } else {
            item.selectedRobots = []
          }
          return item
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.auditOpen = false;
      this.auditRobotOpen = false;
      this.addRobotOpen = false;
      this.reset();
    },
    auditCancel() {
      this.auditOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        clientName: null,
        emailAddr: null,
        password: null,
        walletBalance: null,
        walletKey: null,
        walletStatus: null,
        robotNum: null,
        robotExTime: null,
        registeredTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        remark: null,
        updateTime: null
      };
      this.resetForm("form");
      this.robotForm = {
        robotId: null,
        clientId: null,
        clientName: null,
        robotTypeId: null,
        robotTypeName: null,
        robotName: null,
        robotTrajectory: null,
        robotExpiredTime: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        type: null
      };
      this.resetForm("robotForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加仓库用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getClient(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改仓库用户";
      });
    },
    // 打开修改机器人
    handleRobotUpdate (row) {
      this._listType()
      this.addRobotOpen = true
      this.robotForm = JSON.parse(JSON.stringify(row))
    },
     /** 审核操作 */
     handleAudit(row) {
      this.reset();
      const id = row.id || this.ids
      getClient(id).then(response => {
        this.form = response.data;
        this.auditOpen = true;
        this.title = "用户钱包审核";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateClient(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.auditOpen = false;
              this.getList();
            });
          } else {
            addClient(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.auditOpen = false;
              this.getList();
            });
          }
        }
      });
    },
    // 机器人类型
    _listType () {
      listRobot({
        pageNum: 1,
        pageSize: 1000
      }).then(res => {
        if (res.code === 200) {
          this.robotTypeOptions = res.rows.filter(item => item.status === '1')
        }
      })
    },
    // 新增机器人
    submitRobotForm () {
      this.$refs["robotForm"].validate(valid => {
        if (valid) {
          if (this.robotForm.robotId) {
            this._updateRobotInfo(this.robotForm)
          } else {
            addRobot(this.robotForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.addRobotOpen = false;
              this.auditRobotOpen = false;
              this.getRobotList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除仓库用户编号为"' + ids + '"的数据项？').then(function() {
        return delClient(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/client/export', {
        ...this.queryParams
      }, `client_${new Date().getTime()}.xlsx`)
    },
    startAll (e) {
      // {sid: [1,2,3,4,5,6], name: ['VGA A3','VGA A4'], status: 1}
      console.log(e)
      const params = {sid: [1, 2, 3, 4, 5, 6, 7], name: [], cid: String(e.id), status: "1", all: 1}
      this._sendWebsocket(params)
    },
    stopAll (e) {
      const params = {sid: [1, 2, 3, 4, 5, 6, 7], name: [], cid: String(e.id), status: "0", all: 1}
      this._sendWebsocket(params)
    },
    hanlderCommand (e, row) {
      console.log(e, row)
      setTimeout(async () => {
        const { selectedRobots, robotName, robots } = row
        // console.log(selectedRobots)
        const robotInfo = robots.find(item => item.robotId === e)
        const isExit = selectedRobots.includes(e) // 判断是否存在
        // console.log(isExit)
        const aName = row.robots.filter(item => selectedRobots.includes(item.robotId)).map(item => item.robotName)
        if (isExit) {
          // 加入进来
          // console.log(aName)
          const updateParams = Object.assign(robotInfo, { status: 1 })
          const params = {sid: selectedRobots, name: aName, cid: String(row.id), status: "1", all: 0}
          this._sendWebsocket(params, updateParams)
        } else {
          // console.log(aName)
          const updateParams = Object.assign(robotInfo, { status: 0 })
          const params = {sid: [e], name: [robotInfo.robotName], cid: String(row.id), status: "0", all: 0}
          this._sendWebsocket(params, updateParams)
        }
        // {sid: 1, name: 'VGA A3', status: 1}
      }, 200)
    },
    handlerChangeCheckbox (scope) {
      console.log(scope)
    },
    async _updateRobotInfo (params) {
      updateRobot(params).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.addRobotOpen = false;
        this.auditRobotOpen = false;
        this.getRobotList();
      });
    },
    //查看机器人列表
    handleRobotList(row){
        this.reset();
        this.robotListOpen = true;
        this.queryRobotParams.clientId = row.id
        listRobot(
          this.queryRobotParams
        ).then(res => {
          if (res.code === 200) {
            this.robotList = res.rows
             this.queryRobotParams.total= res.total
          }
        })
    },
    handleAddRobot(row){
      console.log("进入新增机器人方法:"+row)
      this.reset();
      this._listType()
      getClient(row.id).then(response => {
        this.robotForm = response.data;
        this.addRobotOpen = true;
        this.robotForm.clientId = response.data.id
        // this.robotForm.clientName = response.data.clientName
        this.title = "新增机器人";
        this.robotForm.clientId = id
      });
    },
    /** 修改机器人按钮操作 */
    handleRobotUpdate(row) {
      this.reset();
      const robotId = row.robotId || this.ids
      getRobot(robotId).then(response => {
        this.robotForm = response.data;
        this.auditRobotOpen = true;
        this.title = "修改用户机器人";
      });
    },
    /** 删除机器人按钮操作 */
    handleRobotDelete(row) {
      const robotIds = row.robotId || this.ids;
      this.$modal.confirm('是否确认删除用户机器人编号为"' + robotIds + '"的数据项？').then(function() {
        return delRobot(robotIds);
      }).then(() => {
        listRobot(
          this.queryRobotParams
        ).then(res => {
          if (res.code === 200) {
            this.robotList = res.rows
             this.queryRobotParams.total= res.total
          }
        })
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    getRobotList() {
      this.loading = true;
      listRobot(this.queryRobotParams).then(response => {
        this.robotList = response.rows;
        this.queryRobotParams.total = response.total;
        this.loading = false;
      });
    },
    // 发送socket指令
    _sendWebsocket (params, updateParams) {
      // console.log(params)
      sendWebsocket(params).then(async res => {
        // console.log(res)
        if (res.code === 200) {
          this.$message.success(params.status === '1' ? '启动指令发送成功' : '停止指令发送成功')
          await this._updateRobotInfo(updateParams)
          await this.getList()
        }
      })
    }
  }
};
</script>
